const moment = require('moment');
const path = require('path');
const schedule = require('node-schedule');
const fs = require('fs');
const data_163 = require('./data_163');
const data_dx = require('./data_dx');
const data360 = require('./data_360');
const dataQQ = require('./data_qq');
const dataBaidu = require('./data_baidu');
const dataToutiao = require('./data_toutiao');
const dataSina = require('./data_sina');
const mail = require('./mail');
const utils = require('./utils');

const get_x_data = async function (suffix, name, source) {
  let filename = suffix + '_' + name;
  let email_filename = filename;

  let save_dir = path.join("e:", "2019nCov", suffix);
  await utils.dirExists(save_dir);

  let save_filename = path.join(save_dir, filename);
  source.get_data(save_filename);

  console.log(save_filename);
  return save_filename;
}

const sendMail = function (user, password, to, attachements) {
  let mail_subject = "疫情数据-" + moment(Date.now()).format('YYYY-MM-DD HH:mm');
  let mail_text = '加油武汉！加油中国！';
  let new_mail = new mail.Mail(user, password, to, mail_subject, mail_text, attachements);
  setTimeout(() => {
    new_mail.send();
  }, 10000);
}

const get_data = async function (user, password, to) {
  let filename = moment(Date.now()).format('YYYYMMDDHHmmss') + ".xlsx";
  let n163_file = await get_x_data('n163', filename, data_163);
  let dx_file = await get_x_data('dx', filename, data_dx);
  let n360_file = await get_x_data('n360', filename, data360);
  let qq_file = await get_x_data('qq', filename, dataQQ);
  let baidu_file = await get_x_data('baidu', filename, dataBaidu);
  let toutiao_file = await get_x_data('toutiao', filename, dataToutiao);
  let sina_file = await get_x_data('sina', filename, dataSina);

  let attachements = [{
    filename: '网易疫情数据-' + filename,
    path: n163_file
  }, {
    filename: '丁香医生疫情数据-' + filename,
    path: dx_file
  }, {
    filename: '360疫情数据-' + filename,
    path: n360_file
  }, {
    filename: '腾讯疫情数据-' + filename,
    path: qq_file
  }, {
    filename: '百度疫情数据-' + filename,
    path: baidu_file
  }, {
    filename: '头条疫情数据-' + filename,
    path: toutiao_file
  }, {
    filename: '新浪疫情数据-' + filename,
    path: sina_file
  }];

  sendMail(user, password, to, attachements);
}

const get_data_schedule = (cron, user, password, to) => {
  schedule.scheduleJob(cron, function () {
    get_data(user, password, to);
  });
}

exports.get_data = get_data;
exports.get_data_schedule = get_data_schedule;